#coding=utf-8
#
# Copyright (C) 2014  NianNian TECH Co., Ltd. All rights reserved.
# Created on May 9, 2014, by Junn
#
from core.managers import BaseManager
from utils import logs
from django.core.cache import cache

def mk_key(id):
    return 'f%s' % id

class FamilyManager(BaseManager):
    
    def create_family(self, name, creator, about='', **extra_fields):
        family = self.model(name=name, creator=creator, about=about, **extra_fields)
        family.save()
        
        family.cache()
        family.add_member(creator)
        return family
    
    def create_default(self, user):
        '''创建默认家庭'''
        return self.create_family(u'', user)

    def get_cached(self, fid):
        family = cache.get(mk_key(fid))
        if not family:
            try:
                family = self.get(id=int(fid), status='O')
                family.cache()
            except self.model.DoesNotExist:
                logs.error('Family not found: %s' % fid)
                return None
            except Exception, e:
                logs.error('get_cached family error: %s' % e)
                return None
            
        return family     
            
    def cache_all(self):
        families = self.filter(status='O')
        for f in families:
            f.cache()
            f.cache_all_members()
        
        logs.info('====================================> All family entities cached.')    

    def get_posts_unread_count(self): # unused now
        ''' get all unread posts count for all user and all families user joined.
        
        return:
            {u1: [(2, 3), (5, 4)], u2: [(3, 5), ], ...}, 
            (family_id, unread_count):  (2, 3)
        '''
        
        from families.models import FamilyShip
        
        fships = FamilyShip.objects.filter(unread_count__gt=0)
        udict = {}
        for fs in fships:
            if not fs.member_id in udict.keys():
                udict[fs.member_id]= []
            udict[fs.member_id].append({'fid': fs.family_id,'unc': fs.unread_count})
                
        #fships.update(unread_count=0)  # TODO:         
        return udict    
    
    

